package com.dps.omc.agent.queue.consumer.tasker.utils;

import com.jcraft.jsch.*;
import org.slf4j.*;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
/**
 * Created by lip on 2016-01-12.
 */
public class JschClient {

    private static final Logger logger = LoggerFactory.getLogger(JschClient.class);
    private String charset = "UTF-8"; // 设置编码格式
    private String user; // 用户名
    private String passwd; // 登录密码
    private String host; // 主机IP
    private JSch jsch;
    private Session session;


    public JschClient(String user, String passwd, String host) {
        this.user = user;
        this.passwd = passwd;
        this.host = host;
    }

    /**
     * 连接到指定的IP
     *
     * @throws JSchException
     */
    public void connect() throws JSchException {
        jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
    }

    /**
     * 执行相关的命令
     */
    public void execCmd() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String command = "";
        BufferedReader reader = null;
        Channel channel = null;

        try {
            while ((command = br.readLine()) != null) {
                channel = session.openChannel("exec");
                ((ChannelExec) channel).setCommand(command);
                channel.setInputStream(null);
                ((ChannelExec) channel).setErrStream(System.err);

                channel.connect();
                InputStream in = channel.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in,
                        Charset.forName(charset)));
                String buf = null;
                while ((buf = reader.readLine()) != null) {
                    logger.info(buf);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSchException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            channel.disconnect();
            session.disconnect();
        }
    }



    public String execCmd(String command) {

        BufferedReader reader1 = null;
        BufferedReader reader2 = null;
        Channel channel = null;
        StringBuffer sb = new StringBuffer();

        try {
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            channel.connect();
            InputStream in1 = channel.getExtInputStream();
            InputStream in2 = channel.getInputStream();
            reader1 = new BufferedReader(new InputStreamReader(in1,
                    Charset.forName(charset)));
            reader2 = new BufferedReader(new InputStreamReader(in2,
                    Charset.forName(charset)));
            String buf1 = null;
            String buf2 = null;

//            2016-05-10 大SQL会发生阻塞,暂时注释 by lp
//            while ((buf1 = reader1.readLine()) != null) {
//                sb.append(buf1);
//                sb.append("\n");
////                System.out.println(buf1);
//                logger.info("read1:"+buf1);
//            }

//            2016-05-10 采用新线程监听read1 by lp
            new Thread(new LogThread(reader1,sb)).start();
            while ((buf2 = reader2.readLine()) != null) {
                sb.append(buf2);
                sb.append("\n");
//                System.out.println(buf2);
                logger.info("read2:"+buf2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSchException e) {
            e.printStackTrace();
        } finally {
            try {
                reader1.close();
                reader2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            channel.disconnect();
            session.disconnect();
        }
//        System.out.println(sb.toString());
        return sb.toString();
    }

    public static void main(String[] args) {
        String host = "10.238.14.178";
        String user = "root";
        String pass = "1q2w3e";
        String cmd="wget http://10.238.14.178:8080/file/e6825cc8d93546c7a3d80dca8486e882 -O 41cd64506f66464891e105e06783a15d.sql; mysql -h 10.238.14.178 -uroot1 -proot testoms<41cd64506f66464891e105e06783a15d.sql; rm -rf 41cd64506f66464891e105e06783a15d.sql;";
        JschClient client = new JschClient(user,pass,host);
        try {
            client.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        client.execCmd(cmd);
    }
}
